package edu.zjut.hjg.saas.web.controller.admin;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jxl.write.Formula;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.document.AbstractJExcelView;

import edu.zjut.hjg.saas.biz.model.Consumption;
import edu.zjut.hjg.saas.biz.model.Kindergarten;
import edu.zjut.hjg.saas.biz.model.PriceType;
import edu.zjut.hjg.saas.biz.model.Subscribe;
import edu.zjut.hjg.saas.biz.model.Tenant;
import edu.zjut.hjg.saas.biz.service.ConsumptionService;
import edu.zjut.hjg.saas.biz.support.Paginated;

@Controller
@RequestMapping("/admin/consumption")
public class ConsumptionManangeController {
    private static final int   PAGE_SIZE = 30;

    @Autowired
    private ConsumptionService consumptionService;

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
    }

    @RequestMapping("/list.htm")
    public String list(
                       @RequestParam(value = "page", required = false, defaultValue = "1") int page,
                       Model model, Date fromDate, Date toDate) {
        if (page < 1) {
            page = 1;
        }
        if (fromDate == null || toDate == null) {
            model.addAttribute("paginated", new Paginated<Consumption>());
        } else {
            model.addAttribute("paginated", consumptionService.listByDateRang(fromDate, toDate,
                    PAGE_SIZE, page));
        }

        String queryUri = "/admin/consumption/list.htm";
        String reportUri = "/admin/consumption/report.htm?page=" + page;
        if (fromDate != null && toDate != null) {
            queryUri = queryUri + "?fromDate=" + DateFormatUtils.format(fromDate, "yyyy-MM-dd")
                    + "&toDate=" + DateFormatUtils.format(toDate, "yyyy-MM-dd");
            reportUri = reportUri + "&fromDate=" + DateFormatUtils.format(fromDate, "yyyy-MM-dd")
                    + "&toDate=" + DateFormatUtils.format(toDate, "yyyy-MM-dd");
            model.addAttribute("fromDate", fromDate);
            model.addAttribute("toDate", toDate);
        }
        model.addAttribute("queryUri", queryUri);
        model.addAttribute("reportUri", reportUri);
        return "admin/consumption";
    }

    @RequestMapping("/report.htm")
    public ModelAndView report(
                               @RequestParam(value = "page", required = false, defaultValue = "1") int page,
                               Date fromDate, Date toDate) {
        if (page < 1) {
            page = 1;
        }
        if (fromDate == null) {
            fromDate = new Date();
        }
        if (toDate == null) {
            toDate = new Date();
        }
        List<Consumption> consumptions = consumptionService.listByDateRang(fromDate, toDate,
                PAGE_SIZE, page).getValues();
        return new ModelAndView(new ReportView(), "consumptions", consumptions).addObject("page",
                page).addObject("fromDate", fromDate).addObject("toDate", toDate);
    }

    public class ReportView extends AbstractJExcelView {

        @SuppressWarnings("unchecked")
        @Override
        protected void buildExcelDocument(Map<String, Object> model, WritableWorkbook workbook,
                                          HttpServletRequest request, HttpServletResponse response)
                throws Exception {
            response.addHeader("Content-Disposition", "attachment; filename=report.xls");

            List<Consumption> consumptions = (List<Consumption>) model.get("consumptions");
            int page = (Integer) model.get("page");
            String fromDate = DateFormatUtils.format((Date) model.get("fromDate"), "yyyy-MM-dd");
            String toDate = DateFormatUtils.format((Date) model.get("toDate"), "yyyy-MM-dd");
            WritableSheet sheet = workbook.createSheet("第 " + page + " 页", 0);
            sheet.addCell(new Label(0, 0, "从 " + fromDate + " 到 " + toDate + " 的租户消费记录信息"));
            sheet.mergeCells(0, 0, 9, 0);

            sheet.addCell(new Label(0, 1, "租户"));
            sheet.addCell(new Label(1, 1, "计价类型"));
            sheet.addCell(new Label(2, 1, "单价(元)"));
            sheet.addCell(new Label(3, 1, "网站域名"));
            sheet.addCell(new Label(4, 1, "花费(元)"));
            sheet.addCell(new Label(5, 1, "描述"));
            sheet.addCell(new Label(6, 1, "发生时间"));
            int size = consumptions.size();
            for (int i = 0; i < size; i++) {
                Consumption consumption = consumptions.get(i);
                Subscribe subscribe = consumption.getSubscribe();
                PriceType priceType = subscribe.getPriceType();
                Kindergarten app = subscribe.getKindergarten();
                Tenant tenant = consumption.getTenant();
                sheet.addCell(new Label(0, i + 2, tenant.getLoginId()));
                sheet.addCell(new Label(1, i + 2, priceType.getChargeType().getName()));
                sheet.addCell(new Label(2, i + 2, priceType.getPrice() + " / "
                        + priceType.getUnit()));
                sheet.addCell(new Label(3, i + 2, app.getSiteDomain()));
                sheet.addCell(new jxl.write.Number(4, i + 2, consumption.getSpend()));
                sheet.addCell(new Label(5, i + 2, consumption.getDescription()));
                sheet.addCell(new Label(6, i + 2, DateFormatUtils.format(
                        consumption.getOccurTime(), "yyyy-MM-dd")));
            }
            sheet.addCell(new Label(0, size + 2, "合计："));
            sheet.addCell(new Formula(4, size + 2, "SUM(e2:e" + (size + 1) + ")"));
        }
    }
}
